package handler

import (
	"context"
	"log"
	"user-server/basic/dao"
	"user-server/basic/global"
	"user-server/internal/model"
	pb "user-server/proto"
)

type UserServer struct {
	pb.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *UserServer) Register(_ context.Context, in *pb.RegisterReqReq) (*pb.RegisterReqResp, error) {
	var user model.User
	dao.GetOneByTel(in.Tel, &user)
	if user.Id != 0 {
		return &pb.RegisterReqResp{
			Msg:  "the user was existed,can not register",
			Code: 500,
		}, nil
	}
	if dao.Phone(in.Tel) {
		log.Println("the phone number is valid")
	} else {
		return &pb.RegisterReqResp{
			Msg:  "the phone number is invalid",
			Code: 500,
		}, nil
	}
	us := model.User{
		Tel:      in.Tel,
		Password: in.Password,
	}
	dao.Create(&us)
	return &pb.RegisterReqResp{
		Msg:  "register init success",
		Code: 200,
	}, nil
}
func (s *UserServer) List(_ context.Context, in *pb.ListReq) (*pb.ListResp, error) {
	var user []model.User
	dao.Find(&user)
	var us []*pb.Item
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	if in.Page == 0 && in.Size == 0 {
		dao.Find(&user)
	} else {
		global.DB.Offset(int(offset)).Limit(int(pageSize)).Find(&user)
	}
	for _, m := range user {
		uss := pb.Item{
			Id:       m.Id,
			Tel:      m.Tel,
			Password: m.Password,
		}
		us = append(us, &uss)
	}
	return &pb.ListResp{
		List: us,
	}, nil
}
